﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using BreadWebAPI.Models;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Auth;
using Microsoft.WindowsAzure.Storage.Table;
using System.Configuration;

namespace BreadWebAPI.Controllers
{
    public class UnlikesController : ApiController
    {
        CloudStorageAccount storageAccount;
        CloudTable table;

        public UnlikesController()
        {
            // need to make this code execute only once
            storageAccount = CloudStorageAccount.Parse(ConfigurationManager.ConnectionStrings["StorageConnectionString"].ConnectionString);

            // Create the table client.
            CloudTableClient tableClient = storageAccount.CreateCloudTableClient();

            // Create the CloudTable object that represents the "favorites" table.
            table = tableClient.GetTableReference("Favorites");

        }


        // POST api/unlikes
        public void Post([FromBody]LikesEntity value)
        {
            try
            {
                // Create a retrieve operation that takes a customer entity.
                TableQuery<LikesEntity> query = new TableQuery<LikesEntity>().Where(
                    TableQuery.GenerateFilterCondition("BreadDate", QueryComparisons.Equal, value.BreadDate));

                IEnumerable<LikesEntity> likes = table.ExecuteQuery(query);
                LikesEntity likeOfDay;
                if (likes != null)
                {
                    likeOfDay = likes.First<LikesEntity>();
                    likeOfDay.Count--;
                }
                else
                {
                    var errorResponse = new HttpResponseMessage();
                    errorResponse.StatusCode = HttpStatusCode.NotFound;
                    errorResponse.Content = new StringContent("No such likes");
                    throw new HttpResponseException(errorResponse);
                }

                // Create the InsertOrReplace TableOperation
                TableOperation insertOrReplaceOperation = TableOperation.InsertOrReplace(likeOfDay);

                // Execute the operation.
                table.Execute(insertOrReplaceOperation);
            }
            catch (Exception ex)
            {
                var errorResponse = new HttpResponseMessage();
                errorResponse.StatusCode = HttpStatusCode.NotFound;
                errorResponse.Content = new StringContent(ex.ToString());
                throw new HttpResponseException(errorResponse);
            }

        }
    }
}
